/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package caesar;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

/**
 * @author triasfahrudin
 */
public class CaesarDec extends MIDlet implements CommandListener{

    private Form formMain;
    private Form formResult;
    private Display display;
    private TextField ciperText, shiftKey;
    private Command dec;

    public CaesarDec() {
        ciperText = new TextField("Cipher text", "", 30, TextField.ANY);
        shiftKey = new TextField("Shift Key", "", 2, TextField.DECIMAL);
        dec = new Command("DEC", Command.OK, 2);

    }

    public void startApp() {
        display = Display.getDisplay(this);
        formMain = new Form("Caesar Dec");
        formMain.append(ciperText);
        formMain.append(shiftKey);
        formMain.addCommand(dec);
        formMain.setCommandListener(this);
        display.setCurrent(formMain);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public void showResult() {
        display = Display.getDisplay(this);
        String sCipherText = ciperText.getString().toUpperCase();
        int iShiftKey = Integer.parseInt(shiftKey.getString());

        iShiftKey = iShiftKey % 26;
        String plainText = "";
        for (int i = 0; i < sCipherText.length(); i++) {
            int asciiValue = (int) sCipherText.charAt(i);
            if (asciiValue < 65 || asciiValue > 90) {
                plainText += sCipherText.charAt(i);
                continue;
            }

            int basicValue = asciiValue - 65;
            //int newAsciiValue = 65 + ((basicValue + iShiftKey) % 26);
            //plainText += (char) newAsciiValue;
            int newAsciiValue;
            if (basicValue - iShiftKey < 0){
                newAsciiValue = 90 - (iShiftKey - basicValue) + 1;                
            } else {
                newAsciiValue = 65 + (basicValue - iShiftKey);
            }
            plainText += (char) newAsciiValue;
        }

        formResult = new Form("Result");
        formResult.append("Plain Text: " + sCipherText + "\nCipher Text: " + plainText);
        //formResult.append("chiper Text: " + plainText);
        formResult.addCommand(new Command("Back", Command.BACK, 1));
        formResult.setCommandListener(this);
        display.setCurrent(formResult);


    }

    public void commandAction(Command c, Displayable d) {
        String label = c.getLabel();
        if (label.equals("DEC")) {
            showResult();
        } else if (label.equals("Back")) {
            display.setCurrent(formMain);
        }

    }
}
